//index.js
const app = getApp()

Page({
  data: {
    topBtns: [
      {label: "待办", active: true },
      {label: "完结", active: false },
      {label: "全部", active: false }
    ],
    todoLists: [],
    renderList:[],
    inputValue: ""
  },

  onLoad: function() {
    this.getRenderList();
  },

  getRenderList: function() {
    const curFilter = this.data.topBtns.find(c => c.active).label;
    let renderList = this.data.todoLists;
    if(curFilter === "待办") {
      renderList = renderList.filter(c => c.status === "todo");
    } else if (curFilter === "完结") {
      renderList = renderList.filter(c => c.status === "done")
    }

    this.setData({
      renderList
    })

  },

  onFilter: function(e) {
    const cur = e.currentTarget.dataset.status;
    const newTopBtns = this.data.topBtns.map(d => {
      return {
        ...d,
        active: d.label === cur
      }
    })
    this.setData({
      topBtns: newTopBtns
    }, () => {
      this.getRenderList();
    })
  },

  checkboxChange:function(e) {
    const items = this.data.todoLists;
    const values = e.detail.value;
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].status = "todo";

      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].label === values[j]) {
          items[i].status = "done";
          break;
        }
      }
    }
    this.setData({
      todoLists: items
    })
  },
  addTodo:function(e) {
    const value = e.detail.value;
    const todoLists = this.data.todoLists;
    const exsit = todoLists.find(c => c.label === value && c.status === "todo");
    if(exsit) {
      wx.showToast({
        title: '该事务已存在',
        icon: 'error',
        duration: 2000
      })
      return;
    }

    todoLists.push({
      label: value,
      status: "todo"
    });
    this.setData({
      todoLists,
      inputValue: ""
    },() => {
      this.getRenderList()
    })
  }

})
